<template>
  <div @keyup.enter="getLoadProduct">
    <input type="text" style="display: none" />
    <el-form class="query-form" :inline="true" :model="params">
      <el-form-item label="名称查询">
        <el-input v-model="params.load_name" placeholder="产品名称查询"></el-input>
      </el-form-item>
      <el-form-item v-show="isSuper">
        <el-button type="primary" @click="edit()">
          <i class="fa fa-plus"></i>
          新增
        </el-button>
      </el-form-item>
    </el-form>

    <loading-wrap>
      <el-table border :data="tableData">
        <el-table-column prop="load_type" label="产品类型"></el-table-column>
        <el-table-column prop="load_name" label="产品名"></el-table-column>
        <el-table-column min-width="150" label="产品描述">
          <template slot-scope="scope">
            <el-popover placement="right" width="360" trigger="hover">
              <span v-html="scope.row.remark"></span>
              <span slot="reference">{{ scope.row.remark | substr(25) }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="产品模式" min-width="150">
          <template slot-scope="scope">
            <el-popover placement="right" width="360" trigger="hover">
              <span v-html="scope.row.productModel"></span>
              <span slot="reference">{{ scope.row.product_model | substr(30) }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column min-width="150" label="目标客户">
          <template slot-scope="scope">
            <el-popover placement="right" width="300" trigger="hover">
              <span v-html="scope.row.load_entity"></span>
              <span slot="reference">{{ scope.row.load_entity | substr(25) }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="担保金额(万元)">
          <template slot-scope="scope">
            {{ scope.row.load_amount }}
          </template>
        </el-table-column>
        <el-table-column label="贷款期限(年)">
          <template slot-scope="scope">
            <!--{{scope.row.loan_term | pureUnit('年')}}-->
            {{ scope.row.loan_term }}
          </template>
        </el-table-column>
        <el-table-column label="更多详情" width="90" align="center">
          <template slot-scope="scope">
            <el-button type="text" class="py-0 px-1" @click="moreInfo(scope.row)">
              更多详情
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" v-if="isSuper" width="120">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑产品信息" placement="bottom">
              <el-button type="text" @click="edit(scope.row)" class="py-0 px-1">
                <i class="fa fa-edit"></i>
              </el-button>
            </el-tooltip>

            <el-tooltip effect="dark" content="编辑准入条件" placement="bottom">
              <el-button type="text" @click="editCondition(scope.row)" class="py-0 px-1">
                <i class="fa fa-check-square-o"></i>
              </el-button>
            </el-tooltip>

            <el-tooltip effect="dark" content="下架担保产品" placement="bottom">
              <el-button class="py-0 px-1 text-danger" type="text" @click="deleteData(scope.row)">
                <i class="fa fa-trash"></i>
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div class="query-pagination">
        <el-pagination
          @current-change="getLoadProduct"
          :current-page.sync="params.index"
          :page-size="params.size"
          layout="total, prev, pager, next, jumper"
          :total="totalCount"
        ></el-pagination>
      </div>
    </loading-wrap>

    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      title="详情"
      top="30px"
      width="680px"
    >
      <div class="dl-wrap">
        <div class="dl-dt">产品名</div>
        <div class="dl-dd">{{ dataInfo.load_name }}</div>
      </div>

      <div class="dl-wrap">
        <div class="dl-dt">产品费率</div>
        <div class="dl-dd">{{ dataInfo.load_rate }}</div>
      </div>

      <div class="dl-wrap">
        <div class="dl-dt">产品描述</div>
        <div class="dl-dd">{{ dataInfo.remark }}</div>
      </div>

      <!-- <div class="dl-wrap">
        <div class="dl-dt">产品类型</div>
        <div class="dl-dd">{{dataInfo.load_type}}</div>
      </div> -->

      <!-- <div class="dl-wrap">
        <div class="dl-dt">产品方案</div>
        <div class="dl-dd">{{dataInfo.load_scheme}}</div>
      </div> -->

      <div class="dl-wrap">
        <div class="dl-dt">准入条件</div>
        <div class="dl-dd" v-loading="conditionLoading">
          <div class="d-flex" v-for="(pc, key) in dataInfo.productCondition" :key="key">
            <div>{{ `${key}、${pc.label}` }}</div>
            <div class="flex-1 ml-3 border-bottom">
              <div v-for="(pcc, index) in pc.children" :key="`pcc-${index}`">
                {{ pcc.cond_des }}：{{ pcc.meet_cond_des }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="dl-wrap">
        <div class="dl-dt">产品模式</div>
        <div class="dl-dd" v-html="dataInfo.productModel"></div>
      </div>

      <div class="dl-wrap">
        <div class="dl-dt">目标客户</div>
        <div class="dl-dd">{{ dataInfo.load_entity }}</div>
      </div>

      <div class="dl-wrap">
        <div class="dl-dt">担保金额</div>
        <div class="dl-dd">{{ dataInfo.load_amount | pureUnit('万年') }}</div>
      </div>

      <div class="dl-wrap">
        <div class="dl-dt">贷款期限</div>
        <div class="dl-dd">{{ dataInfo.loan_term | pureUnit('年') }}</div>
      </div>

      <!-- <div class="dl-wrap">
        <div class="dl-dt">风控方式</div>
        <div class="dl-dd"
             v-html="formatLine(dataInfo.control_focus)"></div>
      </div> -->

      <div class="dl-wrap">
        <div class="dl-dt">反担保方式</div>
        <div class="dl-dd" v-html="formatLine(dataInfo.guar_measures)"></div>
      </div>

      <div class="dl-wrap">
        <div class="dl-dt">办理流程</div>
        <div class="dl-dd" v-html="formatLine(dataInfo.process_des)"></div>
      </div>

      <div class="dl-wrap">
        <div class="dl-dt">资料清单</div>
        <div class="dl-dd" v-html="formatLine(dataInfo.submit_list)"></div>
      </div>

      <div class="dl-wrap">
        <div class="dl-dt">贷后管理</div>
        <div class="dl-dd" v-html="formatLine(dataInfo.post_loan_des)"></div>
      </div>
    </el-dialog>

    <form-component
      ref="fc"
      :auto-init="false"
      :form-data="formData"
      :formAppend="{}"
      :table-data="editData"
      :idAppend="false"
      :table-id="tableId"
      :table-name="tableName"
      :visible.sync="editVisible"
      @success="getLoadProduct"
    ></form-component>

    <el-dialog
      :visible.sync="condDialogVisible"
      title="准入条件"
      :close-on-click-modal="false"
      top="30px"
    >
      <button type="button" class="btn btn-outline-primary mb-3" @click="onCondEdit()">
        添加准入条件
      </button>

      <div class="row font-weight-bold border-bottom border-top">
        <div class="col-3">
          <div class="py-2">准入条件</div>
        </div>
        <div class="col-3">
          <div class="py-2">指标名</div>
        </div>
        <div class="col-3">
          <div class="py-2">指标内容</div>
        </div>
        <div class="col-3">
          <div class="py-2">操作</div>
        </div>
      </div>

      <div
        class="row border-bottom"
        v-for="(cond, key) in dataInfo.productCondition"
        :key="`cond-${key}`"
      >
        <div class="col-3">
          <div class="p-2">{{ `${key}、${cond.label}` }}</div>
        </div>
        <div class="col-9">
          <div
            class="row border-left"
            style="min-height: 35px"
            v-for="(d, index) in cond.children"
            :key="`cond-detail-${index}`"
            :class="{ 'border-bottom': index < cond.children.length - 1 }"
          >
            <div class="col-4">{{ d.cond_des }}</div>
            <div class="col-4">{{ d.meet_cond_des }}</div>
            <div class="col-4">
              <button type="button" class="btn btn-sm text-info" @click="onCondEdit(d)">
                修改
              </button>
              <button type="button" class="btn btn-sm text-danger" @click="onCondDelete(d)">
                删除
              </button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="condEditDialogVisible"
      top="30px"
      :close-on-click-modal="false"
      width="600px"
      append-to-body
    >
      <el-form label-width="110px">
        <el-form-item label="准入条件类型" v-show="!condDetail.credit_load_product_condition_id">
          <el-select v-model="condDetail.cond_type">
            <el-option
              v-for="(p, key) in enumLoadProduct"
              :key="`lp-${key}`"
              :label="p"
              :value="key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指标名">
          <el-input v-model="condDetail.cond_des"></el-input>
        </el-form-item>
        <el-form-item label="指标内容">
          <el-input v-model="condDetail.meet_cond_des"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="editLoading" @click="onSaveCond()">保存</el-button>
          <el-button @click="condEditDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import FormComponent from '@/components/FormComponent'
import { formatLine } from '@/common/plugins/tools/format'
import { enumLoadProduct } from '@/credit/plugins/enum'

export default {
  components: {
    FormComponent,
  },
  props: {},
  mixins: [
    {
      methods: {
        formatLine,
      },
    },
  ],
  data() {
    return {
      enumLoadProduct,
      params: {
        index: 1,
        size: 10,
        load_name: '',
        'service_id.eq': '',
      },
      tableData: [],
      totalCount: 0,
      formData: {
        load_name: { type: 'text', label: '产品名称', value: '', required: true },
        load_amount: { type: 'text', label: '担保金额', value: '', required: true, unit: '万元' },
        loan_term: { type: 'text', label: '贷款期限', value: '', required: true, unit: '年' },
        load_rate: { type: 'number', label: '担保费率', value: '', required: true, unit: '%' },
        load_type: { type: 'text', label: '产品类型', value: '' },
        remark: { type: 'textarea', label: '产品描述', value: '' },
        // load_scheme: { type: 'textarea', label: '产品方案', value: '' },
        product_model: { type: 'textarea', label: '产品模式', value: '', rows: 5 },
        load_entity: { type: 'textarea', label: '目标客户', value: '', rows: 5 },
        control_focus: { type: 'textarea', label: '风控方式', value: '', rows: 5 },
        post_loan_des: { type: 'textarea', label: '贷后管理', value: '', rows: 5 },
        guar_measures: { type: 'textarea', label: '反担保方式', value: '', rows: 5 },
        process_des: { type: 'textarea', label: '办理流程', value: '', rows: 5 },
        submit_list: { type: 'textarea', label: '资料清单', value: '', rows: 5 },
      },
      editData: {},
      tableId: '',
      tableName: 'credit_load_product',
      editVisible: false,
      dialogVisible: false,
      dataInfo: {},
      conditionLoading: false,
      condDialogVisible: false,
      condEditDialogVisible: false,
      condDetail: {
        cond_des: '',
        cond_type: 1,
        meet_cond_des: '',
        credit_load_product_id: '',
        credit_load_product_condition_id: '',
      },
      editLoading: false,
    }
  },
  computed: {
    org() {
      return this.$store.getters.org
    },
    user() {
      return this.$store.getters.user
    },
    isSuper() {
      return ['org_credit_super', 'org_corp'].includes(this.user.job)
    },
  },
  watch: {},
  created() {
    this.getLoadProduct()
  },
  mounted() {},
  methods: {
    getLoadProduct() {
      this.tableData = []
      this.$api
        .getData('credit', this.tableName, this.params, { create_time: 'desc' })
        .then(res => {
          if (res && res.data) {
            this.tableData = (res.data.data || []).map(item => {
              item.productModel = formatLine(item.product_model)
              item.productCondition = {}
              item.hasCondition = false
              return item
            })
            this.totalCount = res.data.totalCount
          }
        })
    },

    async getLoadProductCondition(row, refresh) {
      if (!refresh && row.hasCondition) {
        return
      }
      this.conditionLoading = true
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'credit_load_product_condition', {
          'credit_load_product_id.eq': row.credit_load_product_id,
        })
      )
      this.conditionLoading = false
      if (res) {
        const data = res.data || []
        Object.keys(enumLoadProduct).forEach(key => {
          row.productCondition[key] = {
            label: enumLoadProduct[key],
            children: [],
          }
        })
        for (const d of data) {
          row.productCondition[d.cond_type].children.push(d)
        }
        row.hasCondition = true
        this.dataInfo = { ...row }
      }
    },

    handleClose() {
      this.dialogVisible = false
    },

    moreInfo(row) {
      this.dialogVisible = true
      this.dataInfo = { ...row }
      this.getLoadProductCondition(row)
    },

    edit(p) {
      this.editVisible = true
      this.tableId = p ? p.credit_load_product_id : ''
      this.editData = p
    },

    deleteData(item) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定下架？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '下架中...'
            let res = ''
            res = await this.$utils.promise(
              this.$api.deleteData('credit', this.tableName, item.credit_load_product_id)
            )
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('下架成功！')
              this.getLoadProduct()
              done()
            } else {
              this.$message.error('下架失败，请重试！')
            }
          } else {
            done()
          }
        },
      }).catch(() => {})
    },

    editCondition(row) {
      this.condDialogVisible = true
      this.dataInfo = { ...row }
      this.getLoadProductCondition(row)
    },

    onCondEdit(row) {
      if (!row) {
        this.condDetail = {
          cond_des: '',
          cond_type: '1',
          meet_cond_des: '',
          credit_load_product_id: '',
          credit_load_product_condition_id: '',
        }
      } else {
        this.condDetail = { ...row }
      }
      this.condEditDialogVisible = true
    },

    onCondDelete(row) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定下架？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '下架中...'
            const [res] = await this.$utils.promise(
              this.$api.deleteData(
                'credit',
                'credit_load_product_condition',
                row.credit_load_product_condition_id
              )
            )
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('下架成功！')
              this.getLoadProductCondition(this.dataInfo, true)
              done()
            } else {
              this.$message.error('下架失败，请重试！')
            }
          } else {
            done()
          }
        },
      }).catch(() => {})
    },

    async onSaveCond() {
      const data = {
        cond_des: this.condDetail.cond_des,
        cond_type: this.condDetail.cond_type,
        meet_cond_des: this.condDetail.meet_cond_des,
      }
      if (this.condDetail.credit_load_product_condition_id) {
        this.editLoading = true
        const [res] = await this.$utils.promise(
          this.$api.updateData(
            'credit',
            'credit_load_product_condition',
            this.condDetail.credit_load_product_condition_id,
            data
          )
        )
        this.editLoading = false
        if (res) {
          this.condEditDialogVisible = false
          this.$message.success('修改成功！')
          this.getLoadProductCondition(this.dataInfo, true)
        } else {
          this.$message.error('修改失败，请重试！')
        }
      } else {
        data.credit_load_product_id = this.dataInfo.credit_load_product_id
        this.editLoading = true
        const [res] = await this.$utils.promise(
          this.$api.addData('credit', 'credit_load_product_condition', data)
        )
        this.editLoading = false
        if (res) {
          this.condEditDialogVisible = false
          this.$message.success('添加成功！')
          this.getLoadProductCondition(this.dataInfo, true)
        } else {
          this.$message.error('添加失败，请重试！')
        }
      }
    },
  },
}
</script>
<style scoped></style>
